<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;

class Orders extends Rest
{
    public $modelName = 'Order'; // model 类名称

    public function GETIndex()
    {
        switch ($this->role) {
            case 0:
                unset($this->param['userId']);
                break;
            case 2:
                $this->param['shopId'] = $this->param['userId'];
                unset($this->param['userId']);
                break;
        }
        if (isset($this->param['Id'])) {
            $res = $this->model()->getDataById($this->param['Id']);
        } else {
            $res = $this->model()->getDataList($this->param);
        }
        $this->result($res, ['msg' => self::$model->getError(), 'data' => $res]);
    }

    public function POSTIndex()
    {
        // TODO 查看兑换人 是店铺还是会员
        $Member = $this->model('Member');
        $Product = $this->model('Product');
        $userInfo = $Member->where(['id' => $this->param['userId']])->find();
        switch ($userInfo['roleId']) {
            case 1:
                // TODO 基本信息获取
                $shopInfo = $Member->where(['id' => $userInfo['shopId']])->find();
                $productInfo = $Product->where(['id' => $this->param['productId']])->find();
                $this->abort($userInfo && $shopInfo && $productInfo, ['请求信息有误']);

                // TODO 支付密码检测
                $this->abort(user_md5($this->param['paypass']) == $Member->where(['id' => $this->param['userId']])->value('paypass'), ['msg' => '支付密码错误!']);

                // TODO 查看是否使用现金
                $totalPrice = $productInfo['productPrice'] * $this->param['productNum']; // 至少扣除的现金
                $costBalance = $totalPrice;
                $this->abort($userInfo['balance'] >= $totalPrice, ['msg' => '现金不足!']);
                $totalPoint = $productInfo['productPoint'] * $this->param['productNum']; // 最多扣除的积分
                $costPoint = $totalPoint;

                if (!isset($this->param['Usebalance']) or $this->param['Usebalance'] != 1) {
                    // 不使用现金 并且积分不足
                    if ($userInfo['point'] < $totalPoint) {
                        $this->error(['msg' => '积分不足!(现金可抵用积分)']);
                    }
                } else {
                    if ($userInfo['point'] < $totalPoint and $userInfo['point'] + $userInfo['balance'] >= ($totalPrice + $totalPoint)) {
                        // 使用现金 积分不足 但是合并支付充足
                        $costPoint = $userInfo['point']; // 积分全部使用
                        // 为店铺返利
                        $costBalance = $totalPrice + ($totalPoint - $costPoint); // 使用现金额度增加
                    }
                }

                $shopRecome = $productInfo['percent'] * $costBalance;
                if ($shopRecome != 0) {
                    $AllRecord[] = [
                        'userId' => $userInfo['shopId'],
                        'username' => $userInfo['shopUsername'],
                        'change' => $shopRecome,
                        'remain' => $shopInfo['balance'] + $shopRecome,
                        'type' => 1,
                        'remark' => '会员兑换商品',
                    ];
                }

                // TODO 生成积分扣除记录
                if ($costPoint != 0) {
                    $AllRecord[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => -$costPoint,
                        'remain' => $userInfo['point'] - $costPoint,
                        'type' => 2,
                        'remark' => '兑换商品',
                    ];
                }

                // TODO 现金兑换记录
                if ($costBalance != 0) {
                    $AllRecord[] = [
                        'userId' => $this->param['userId'],
                        'username' => $userInfo['username'],
                        'change' => -$costBalance,
                        'remain' => $userInfo['balance'] - $costBalance,
                        'type' => 1,
                        'remark' => '兑换商品',
                    ];
                }

                // TODO 生成订单数据
                $orderData = [
                    'productId' => $this->param['productId'],
                    'shopId' => $userInfo['shopId'],
                    'userId' => $this->param['userId'],
                    'productName' => $productInfo['productName'],
                    'totalPrice' => $totalPrice,
                    'username' => $userInfo['username'],
                    'productNum' => $this->param['productNum'],
                    'shopName' => $userInfo['shopUsername'],
                    'province' => $userInfo['province'],
                    'city' => $userInfo['city'],
                    'hometown' => $userInfo['hometown'],
                    'detailAddress' => $userInfo['detailAddress'],
                ];
                $Member->startTrans();
                try {
                    // TODO 操作数据库生成数据
                    $this->model('MemberRecord')->insertAll($AllRecord);

                    $Member->where(['id' => $this->param['userId']])->setDec('balance', $costBalance);
                    $Member->where(['id' => $this->param['userId']])->setDec('point', $costPoint);
                    if ($shopRecome != 0) {
                        $Member->where(['id' => $userInfo['shopId']])->setInc('balance', $shopRecome);
                    }

                    $res = $this->model()->createData($orderData);
                    $Member->commit();
                } catch (\Exception $e) {
                    $Member->rollback();
                    $this->error(['msg' => $e->getMessage()]);
                }
                break;
            case 2:
                $shopInfo = $Member->where(['id' => $this->param['userId']])->find();
                $this->abort(isset($this->param['shopUserId']), ['msg' => '请选择会员']);
                $userInfo = $Member->where(['id' => $this->param['shopUserId']])->find();
                // 店铺兑换只能兑换 商品type为 0 的 商品 并扣除电子币
                $productInfo = $Product->where(['id' => $this->param['productId'], 'type' => 2])->find();
                $id = $this->param['shopUserId'];
                $this->abort($productInfo, ['msg' => '商品不存在或不支持此类兑换']);
                // 兑换数量
                $number = $this->param['productNum'];
                // 总价格
                $price = $productInfo['productPrice'] * $number;

                $insertData['regionId'] = $shopInfo['regionId'];
                $insertData['regionUsername'] = $shopInfo['regionUsername'];
                $insertData['regionCellphone'] = $shopInfo['regionCellphone'];

                // 省
                $insertData['provinceId'] = $shopInfo['provinceId'];
                $insertData['provinceUsername'] = $shopInfo['provinceUsername'];
                $insertData['provinceCellphone'] = $shopInfo['provinceCellphone'];

                // 市
                $insertData['cityId'] = $shopInfo['cityId'];
                $insertData['cityUsername'] = $shopInfo['cityUsername'];
                $insertData['cityCellphone'] = $shopInfo['cityCellphone'];

                // 店铺
                $insertData['shopId'] = $shopInfo['id'];
                $insertData['shopUsername'] = $shopInfo['username'];
                $insertData['shopCellphone'] = $shopInfo['cellphone'];

                $Member->startTrans();
                try {

                    // 新增普通用户
                    // TODO 扣除店铺对应的电子币 并生成记录
                    $emoney = $shopInfo['emoney'];
                    if ($emoney < $price) {
                        throw new \Exception('电子币余额不足');
                    }
                    $Member->where(['id' => $insertData['shopId']])->setDec('emoney', $price);
                    $record[] = [
                        'userId' => $insertData['shopId'],
                        'username' => $userInfo['shopUsername'],
                        'change' => -$price,
                        'remain' => $emoney - $price,
                        'type' => 3,
                        'remark' => '重消兑换',
                    ];

                    // TODO 给用户加上相应积分
                    $point = $Member->where(['id' => $id])->value('point');
                    $Member->where(['id' => $id])->setInc('point', $productInfo['returnPoint']);

                    $record[] = [
                        'userId' => $id,
                        'username' => $userInfo['username'],
                        'change' => $price,
                        'remain' => $point + $productInfo['returnPoint'],
                        'type' => 2,
                        'remark' => '重消兑换',
                    ];

                    // TODO 为该用户不同的上级发放相应的返现金额  并生成记录
                    //1 重复消费 600 给自己
                    $referPrice = 600 * $number;
                    $balance = $Member->where(['id' => $id])->value('balance');
                    $Member->where(['id' => $id])->setInc('balance', $referPrice);

                    // 洗肠次数累加
                    $Member->where(['id' => $id])->setInc('washTimes', $number * $productInfo['washTimes']);
                    // TODO 给用户增加响应的洗肠次数 并生成记录
                    $WashRecord = [
                        'userId' => $id,
                        'shopId' => $userInfo['shopId'],
                        'shopUsername' => $userInfo['shopUsername'],
                        'washUsername' => $userInfo['username'],
                        'artificer' => '',
                        'washTimes' => $number * $productInfo['washTimes'],
                        'remark' => '重消兑换',
                    ];

                    $record[] = [
                        'userId' => $id,
                        'username' => $userInfo['username'],
                        'change' => $referPrice,
                        'remain' => $balance + $referPrice,
                        'type' => 1,
                        'remark' => '重复消费',
                    ];

                    //2 店铺
                    $referPrice = 1600 * $number;
                    $balance = $Member->where(['id' => $insertData['shopId']])->value('balance');
                    $Member->where(['id' => $insertData['shopId']])->setInc('balance', $referPrice);

                    $record[] = [
                        'userId' => $insertData['shopId'],
                        'username' => $userInfo['shopUsername'],
                        'change' => $referPrice,
                        'remain' => $balance + $referPrice,
                        'type' => 1,
                        'remark' => '会员重复消费',
                    ];

                    //3 区县代
                    $referPrice = 400 * $number;
                    $balance = $Member->where(['id' => $insertData['regionId']])->value('balance');
                    $Member->where(['id' => $insertData['regionId']])->setInc('balance', $referPrice);

                    $record[] = [
                        'userId' => $insertData['regionId'],
                        'username' => $userInfo['regionUsername'],
                        'change' => $referPrice,
                        'remain' => $balance + $referPrice,
                        'type' => 1,
                        'remark' => '会员重复消费',
                    ];

                    //4 市代
                    $referPrice = 200 * $number;
                    $balance = $Member->where(['id' => $insertData['cityId']])->value('balance');
                    $Member->where(['id' => $insertData['cityId']])->setInc('balance', $referPrice);

                    $record[] = [
                        'userId' => $insertData['cityId'],
                        'username' => $userInfo['cityUsername'],
                        'change' => $referPrice,
                        'remain' => $balance + $referPrice,
                        'type' => 1,
                        'remark' => '会员重复消费',
                    ];

                    // TODO 为会员生成订单信息
                    $orderData = [
                        'productId' => 1,
                        'shopId' => $insertData['shopId'],
                        'userId' => $id,
                        'productName' => $productInfo['productName'],
                        'totalPrice' => $productInfo['productPrice'] * 1, // 默认购买一份
                        'username' => $userInfo['username'],
                        'productNum' => $number,
                        'type' => 2, // 电子币消费
                        'shopName' => $userInfo['shopUsername'],
                        'province' => $userInfo['province'],
                        'city' => $userInfo['city'],
                        'hometown' => $userInfo['hometown'],
                        'detailAddress' => $userInfo['detailAddress'],
                    ];

                    // TODO 操作数据库生成数据
                    $this->model('MemberRecord')->insertAll($record);

                    $res = $this->model()->createData($orderData);
                    $Member->commit();
                } catch (\Exception $e) {
                    $Member->rollback();
                    $this->error(['msg' => $e->getMessage()]);
                }

                break;
            default:
                $this->error(['msg' => '权限错误!']);
                break;
        }

        $this->result($res, ['msg' => self::$model->getError()]);
    }


    /**
     * 订单批量操作
     *
     * @return void
     */
    public function POSTEnables()
    {
        $res = $this->model()->enableDatas($this->param['ids'], $this->param['orderStatus']);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

}
